package xml;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 孙许
 * @date 2018-04-20
 * @description
 */
public class ReadxmlBySax {
    private static final Logger logger = LogManager.getLogger(ReadxmlBySax.class);
    private static SAXParserFactory factory;
    private static SAXParser parser;

    static {
        try {
            factory = SAXParserFactory.newInstance();
            parser = factory.newSAXParser();
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        }
    }

    private List<Book> list;
    private Book book;
    // 存放当前节点值
    private String content;

    public List<Book> getBooks(File fileName) throws Exception {
        DefaultHandler handler = new DefaultHandler() {
            @Override
            public void startDocument() throws SAXException {
                super.startDocument();
                logger.debug("startDocument...");
                logger.debug("开始解析xml文件");
                list = new ArrayList<Book>();
            }

            @Override
            public void endDocument() throws SAXException {
                super.endDocument();
                logger.debug("endDocument...");
                logger.debug("xml文件解析完毕");
            }

            @Override
            public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
                super.startElement(uri, localName, qName, attributes);
                logger.debug("startElement...");
                // 当节点名为book时，获取book的属性id
                if ("book".equals(qName)) {
                    book = new Book();
                    String id = attributes.getValue("id");
                    book.setId(Integer.parseInt(id));
                }
                logger.debug("startElement...");
                logger.debug("uri: " + uri);
                logger.debug("localName: " + localName);
                logger.debug("qName: " + qName);
            }

            @Override
            public void endElement(String uri, String localName, String qName) throws SAXException {
                super.endElement(uri, localName, qName);
                logger.debug("endElement...");
                if ("name".equals(qName)) {
                    book.setName(content);
                }
                if ("author".equals(qName)) {
                    book.setAuthor(content);
                }
                if ("year".equals(qName)) {
                    book.setYear(Integer.parseInt(content));
                }
                if ("price".equals(qName)) {
                    book.setPrice(Double.parseDouble(content));
                }
                if ("book".equals(qName)) {
                    list.add(book);
                    book = null;
                }
            }

            @Override
            public void characters(char[] ch, int start, int length) throws SAXException {
                super.characters(ch, start, length);
                content = new String(ch, start, length);
                if ("".equals(content)) {
                    content = "我是空格";
                }
                if (content == null) {
                    content = "我是null";
                }
                if ("\n".equals(content)) {
                    content = "我是换行符";
                }
                logger.debug("characters...");
                logger.debug("content: " + content);
            }
        };

        parser.parse(fileName, handler);

        return list;
    }


}
